home *** CD-ROM | disk | FTP | other *** search
- Path: news.uni-jena.de!news
- From: mkt@isun04.inf.uni-jena.de (Tilo Koerbs)
- Newsgroups: comp.lang.c++
- Subject: Re: passing pointers to functions
- Date: 1 Feb 1996 11:28:02 GMT
- Organization: Lehrstuhl fuer Rechnerarchitektur- und kommunikation, FSU Jena
- Message-ID: <4eq842$fpu@fsuj01.rz.uni-jena.de>
- References: <Pine.A32.3.91.960131105301.69201A-100000@red.weeg.uiowa.edu>
- Reply-To: mkt@isun04.inf.uni-jena.de
- NNTP-Posting-Host: isun07.inf.uni-jena.de
-
- > I want to pass an empty pointer to a function.
- >
- > Inside the function, I create an array. Then I set the
- > pointer_to_array = &A[0]. Finally at the end of the function I return
- > the pointer_to_array to my main.
- >
- > void main ()
- > {
- > int *A1 = NULL;
- > A1 = MakeArray(A1);
- > cout << "First element in Array is" << *A1;
- > }
- >
- > My specific question is: what should my function header look like?
- > My general question is: what are the rules for passing (and returning)
- > pointers to functions w/ call by reference,parameter, and constant reference?
-
- Your questions are looking a little bit too general!
- I try to give some answers:
-
- Your function will pass the argument and the return value by value.
- int * MakeArray(int *);
- But what for do you use the argument in the function?
- If you always pass a so called NULL-pointer to the function, then it
- knows this fact already and needs no argument to tell it!
- int * MakeArray() {
- int * A = new int[10];
- pointer_to_array = A; // This is the same as: p_t_a = &A[0];
- // An array is automatically converted to a pointer
- // to its first argument!
- return pointer_to_array;
- }
- // The whole function can be written as: return new int[10]; // Thats all!
-
- To the general question:
- You can pass anything (ints, pointers, ...) by value (the default).
- So a copy of the object is created and then passed.
- You can pass anything by reference (except that there are no references
- on references). So a reference (a hidden pointer) to the object
- is passed.
- Example:
- void MakeArray(int*& A) { // A reference to a pointer.
- A = new int[10]; // The A given to the function is
- // manipulated.
- }
- This function works the same as the others.
-
- I suggest you read a book for more details.
- Bye
-
-
-